/*
 * @Author: xmily
 * @Date: 2021-12-03 15:40:18
 * @LastEditors: xmily
 * @LastEditTime: 2023-05-18 00:13:30
 * @FilePath: \glxxapi\routes\sys\afterclasssvr.js
 * @Description:
 *
 * Copyright (c) 2022 by xmily/mxthink.com.cn, All Rights Reserved.
 */
const router = require("koa-router")();
const aftclassrv = require("../../models/AfterClassService/application.js");
const aftclassrv_addstatus = require("../../models/AfterClassService/addstatus.js");
const base = require("../../models/Fjxx.js");
const sitecfg = require("../../cfg/siteconfig.js");
const aftclassrv_lesson = require("../../models/AfterClassService/lesson.js");
const commMethod=require("../../cfg/commMethod.js")
router.prefix("/sys/afterclasssvr");

var term=""
var termlist=[]
router.use(async (ctx, next) => {
  termlist = await commMethod.getTermList();
  term = termlist.sort()[termlist.length - 1];
  await next();
});

//获取课后服务训练队类型的课程
router.get("/gettraininglesson", async (ctx, next) => {
  try {
    let res = await aftclassrv_lesson.GetByQuery(
      {
        schoolname: sitecfg.schoolname,
        term: term,
        type:"training"
      },
      { lessonname: 1, _id: 0, limit: 1, teacher: 1 }
    );
    console.log(res);
    ctx.body = { error: false, result: res };
  } catch (err) {
    throw new Error("获取课后服务训练队课程时出错:[" + err + "]");
  }
});
//批量修改课后服务申请信息
router.post("/updateByQuery", async (ctx, next) => {
  let token = ctx.request.token;
  let query = ctx.request.body.query;
  let update = ctx.request.body.update;
  let options = ctx.request.body.options;
  try {
    let res = await aftclassrv.UpdateByQuery(query, update, options);
    // let res = await aftclassrv.GetByQuery({
    //   _id: {
    //     $in: [
    //       "62125a8f336a782324a3df8d",
    //       "62125cd2336a782324a3df98"
    //     ],
    //   },
    // });
    ctx.body = { error: false, result: res };
  } catch (err) {
    throw new Error("根据查询批量修改课后服务信息时出错:[" + err + "]");
  }
});
//根据班级和月份获取课后服务记录信息
router.post("/getstudentinfo", async (ctx, next) => {
  try {
    //获取课后服务学生
    let token = ctx.request.token;
    // let query = ctx.request.body.month;
    let query=ctx.request.body.query;
    // let classno=ctx.request.body.classno;
    // let classno = token.classno;
    // let stuinfolist = await aftclassrv.GetByQuery({
    //   month: query,
    //   classno: classno,
    // });
    let stuinfolist = await aftclassrv.GetByQuery(query);
    ctx.body = { error: false, result: stuinfolist };
  } catch (err) {
    throw new Error("获取课后服务报名学生时出错:[" + err + "]");
  }
});
//获取所有指定月份的课后服务记录信息
router.post("/getallstudentinfo", async (ctx, next) => {
  try {
    //获取课后服务学生
    let token = ctx.request.token;
    let query = ctx.request.body.month;
    // let classno = ctx.request.body.classno;
    let stuinfolist = await aftclassrv.GetByQuery(
      {
        month: query,
        term:term,
        // classno: classno,
      },
      { applicationwrite: 0, safewrite: 0 }
    );
    ctx.body = { error: false, result: stuinfolist };
  } catch (err) {
    throw new Error("获取所有指定月份的课后服务记录信息时出错:[" + err + "]");
  }
});
//PC端保存社团申请
router.post("/saveapplication", async (ctx, next) => {
  try {
    //保存课后服务申请
    //   let userinfo = ctx.request.token;
    let interestinfo = ctx.request.body.interestinfo;
    interestinfo.classno = interestinfo.classno;
    interestinfo.stuname = interestinfo.stuname;
    interestinfo.stuid = interestinfo.stuid;
    interestinfo.term = term;
    interestinfo.schoolname = sitecfg.schoolname;
    interestinfo.status = ctx.state.aftclssvrStatus.get("unAllot");
    let applicationinfo = await aftclassrv.Save(interestinfo);
    ctx.body = { error: false, result: applicationinfo };
  } catch (err) {
    throw new Error("保存时出错:[" + err + "]");
  }
});
//PC端删除社团申请
router.post("/delapplication", async (ctx, next) => {
  let query = ctx.request.body.query;
  // query.stuid=token.userid
  try {
    let applicationinfo = await aftclassrv.Del(query);
    ctx.body = { error: false, result: applicationinfo };
  } catch (err) {
    throw new Error("删除时出错:[" + err + "]");
  }
});

//根据当前学校获取申请列表中的所有班级
router.get("/getclassno", async (ctx, next) => {
  let query = [
    {
      $match: {
        term: term,
      },
    },
    {
      $group: {
        _id: "$classno",
      },
    },
    {
      $sort: {
        _id: -1,
      },
    },
  ];
  try {
    let applicationinfo = await aftclassrv.myAggregate(query);
    ctx.body = { error: false, result: applicationinfo };
  } catch (err) {
    throw new Error("删除时出错:[" + err + "]");
  }
});

router.get("/getaddstatus", async (ctx, next) => {
  let term=ctx.query.term;
  let month=ctx.query.month;
  try {
    let result = await aftclassrv_addstatus.GetByQuery({ term: term,month:month});
    ctx.body = { error: false, result: result };
  } catch (err) {
    throw new Error("获取PC端自主添加学生课后服务数据时出错:[" + err + "]");
  }
});


router.get("/summary", async (ctx, next) => {
  let month = ctx.query.month;
  // let schoolname = sitecfg.schoolname;
  // let resarr = [];
  
  //特殊类型统计
  let matcharr = [
    {
      match: {
        term: term,
        month: month,
        $and: [{ status: { $ne: "申请退出" } }, { status: { $ne: "退出" } }], //参加课后服务的总人数
      },
      typename: "总人数",
      type:"special",
      id: 1,
    },
    {
      match: {
        term: term,
        month: month,
        $and: [{ status: { $ne: "申请退出" } }, { status: { $ne: "退出" } }], //参加基础课的总人数
        // selected:{$nin:["棒球","排球","合唱","篮球"]},    //因社团未分班造成基础课人数不对而注释
        baselesson: true,
      },
      typename: "基础课",
      type:"special",
      id: 2,
    },
    {
      match: {
        term: term,
        month: month,
        $and: [{ status: "申请退出" }], //申请退出的人数
      },
      typename: "申请退出",
      type:"special",
      id: 4,
    },
    {
      match: {
        term: term,
        month: month,
        $and: [{ status: "退出" }], //退出的人数
      },
      typename: "退出",
      type:"special",
      id: 4,
    },
    {
      match: {
        term: term,
        month: month,
        $and: [{ status: "未分配" }], //未分配的人数
      },
      typename: "未分配",
      type:"special",
      id: 4,
    },
    {
      match: {
        term: term,
        month: month,
        $and: [{ status: "再入申请" }], //再入申请的人数
      },
      typename: "再入申请",
      type:"special",
      id: 4,
    },
  ];
  try {
    let interestlesson = await aftclassrv_lesson.GetByQuery(
      {
        schoolname: sitecfg.schoolname,
        term: term,
      },
      { lessonname: 1, _id: 0, limit: 1, teacher: 1,type:1 }
    );
    //兴趣班类型统计
    interestlesson.forEach((element) => {
      if(element.type=="training"){
        matcharr.push({
          match: {
            term: term,
            month: month,
            $and: [{ status: "已分配" }],
            trainingTeam: element.lessonname,
          },
          typename: element.lessonname,
          type:element.type,
          id: 3,
        });
      }else if(element.type="interest"){
        matcharr.push({
          match: {
            term: term,
            month: month,
            $and: [{ status: "已分配" }],
            selected: element.lessonname,
          },
          typename: element.lessonname,
          type:element.type,
          id: 3,
        });
      }
      
    });

    //取得班级列表
    let query = [
      {
        $match: {
          term: term,
        },
      },
      {
        $group: {
          _id: "$classno",
        },
      },
      {
        $sort: {
          _id: 1,
        },
      },
    ];
    let classno = await aftclassrv.myAggregate(query);
    console.log(classno);

    let resarr = [];
    let promiseArr = matcharr.map(async (doc) => {
      let res2 = await aftclassrv.myAggregate([
        {
          $match: doc.match,
        },
        {
          $project: {
            applicationwrite: 0,
            safewrite: 0,
          },
        },
        {
          $group: {
            _id: "$classno",
            count: { $sum: 1 },
          },
        },
        {
          $sort: {
            _id: 1,
          },
        },
      ]);
      // resarr.push({ typename: doc.typename, data: res2, id: doc.id });
      return { typename: doc.typename,type:doc.type, data: res2, id: doc.id };
    });
    let result = await Promise.all(promiseArr);
    console.log(result);
    ctx.body = { error: false, result: cv(result, classno) };
  } catch (err) {
    throw new Error("获取课后服务社团课程时出错:[" + err + "]");
  }
});

//转换各类统计(转换成按班统计)
function cv(arr, classno) {
  let newarr = [];
  classno.forEach((doc) => {
    newarr.push({ classno: doc._id });
  });
  arr.forEach((a) => {
    a.data.forEach((d) => {
      let index = newarr.findIndex((c) => c.classno == d._id);
      // let typename = a.typename;
      newarr[index][a.typename] = d.count;
    });
  });
  return newarr;
}

module.exports = router;
